package by.gravity.drive_track.fragments;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import by.gravity.common.fragment.CommonDialogFragment;
import by.gravity.drive_track.AppIntents;
import by.gravity.drive_track.R;
import by.gravity.drive_track.widget.AutoCompleteTextView;

public class AddRouteDialog extends CommonDialogFragment implements AppIntents {

	public static final String TAG = AddRouteDialog.class.getSimpleName();

	private AutoCompleteTextView mAutoCompleteTextView;

	private String mPointName;

	public static AddRouteDialog newInstance(int number) {
		Bundle bundle = new Bundle();
		bundle.putInt(ARG_POINT_NUMBER, number);

		AddRouteDialog dialog = new AddRouteDialog();
		dialog.setArguments(bundle);
		return dialog;
	}

	@Override
	public Dialog onCreateDialog(Bundle savedInstanceState) {
		View view = LayoutInflater.from(getActivity()).inflate(R.layout.route_main_item, null);
		initView(view);
		Builder builder = new AlertDialog.Builder(getActivity());
		builder.setTitle(R.string.add_point);
		builder.setView(view);
		builder.setPositiveButton(R.string.ok, new OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				Intent intent = new Intent(ADD_ADDITIONAL_POINT_INTENT);
				intent.putExtra(ARG_POINT_NAME, mPointName);
				sendBroadcast(intent);
				dismiss();
			}
		}).setNegativeButton(R.string.cancel, new OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {

			}
		});
		getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
		return builder.show();

	}

	private void initView(View view) {
		mAutoCompleteTextView = (AutoCompleteTextView) view.findViewById(R.id.text);
		view.setTag(getArguments().getInt(ARG_POINT_NUMBER) + DIALOG_SPLIT);
	}

	@Override
	protected void addIntentFilter(IntentFilter filter) {
		filter.addAction(SHOW_ADD_ROUTE_DIALOG_INTENT);
		filter.addAction(HIDE_ADD_ROUTE_DIALOG_INTENT);
		filter.addAction(ADD_POINT_NAME_INTENT);
	}

	@Override
	protected void onBroadcastReceive(Intent intent,String intentAction) {
		if (intentAction.equals(SHOW_ADD_ROUTE_DIALOG_INTENT)) {
			if (getDialog() != null) {
				getDialog().show();
			}
		} else if (intentAction.equals(HIDE_ADD_ROUTE_DIALOG_INTENT)) {
			if (getDialog() != null) {
				getDialog().hide();
			}
		} else if (intentAction.equals(ADD_POINT_NAME_INTENT)) {
			mPointName = intent.getStringExtra(ARG_POINT_NAME);
			mAutoCompleteTextView.setText(mPointName);
		}
	}

}
